from typing import TypeVar, Union

from zkl_pyutils_registries.basics import Matcher, SpecialKey, UNSET

AnyKey = TypeVar("AnyKey")
AnyQuery = TypeVar("AnyQuery")
AnyMatch = TypeVar("AnyMatch")

TolerantKey = Union[AnyQuery, SpecialKey]
TolerantQuery = Union[AnyKey, SpecialKey]
TolerantMatch = Union[tuple[int], tuple[int, AnyMatch]]


class TolerantMatcher(Matcher[TolerantKey, TolerantQuery, TolerantMatch]):
    def __init__(self, base: Matcher[AnyQuery, AnyKey, AnyMatch]):
        self._base = base

    def match(self, query: TolerantQuery, key: TolerantKey) -> TolerantMatch:
        if query is UNSET:
            if key is UNSET:
                return 0,
            else:
                return -1,
        else:
            if key is UNSET:
                return -1,
            else:
                return 0, self._base.match(query, key)
